<template>
  <div class="drone-warehouse-home">
    <el-container style="height: 100vh">
      <!-- 侧边导航栏 -->
      <el-aside width="220px" class="sidebar">
        <div class="sidebar-title">
          <span>无人机出入库管理系统</span>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="el-menu-vertical-demo"
          @select="handleMenuSelect"
        >
          <el-menu-item index="warehouse" v-if="accountNumber == 'admin'">
            <el-icon>
              <OfficeBuilding />
            </el-icon>
            <span>仓库管理</span>
          </el-menu-item>
          <el-menu-item index="inbound" v-if="accountNumber == 'admin'">
            <el-icon>
              <Upload />
            </el-icon>
            <span>入库管理</span>
          </el-menu-item>
          <el-menu-item index="drone-info" v-if="accountNumber != 'lingdao'">
            <el-icon>
              <Suitcase />
            </el-icon>
            <span>无人机信息管理</span>
          </el-menu-item>
          <el-menu-item index="outbound" v-if="accountNumber == 'admin'">
            <el-icon>
              <Download />
            </el-icon>
            <span>出库管理</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <!-- 右侧内容区 -->
      <el-main class="main-content">
        <div v-if="activeMenu === 'warehouse'">
          <!-- 右侧内容区顶部栏 -->
          <div class="right-top-bar">
            <div class="top-bar-left">
              <span class="breadcrumb">
                <el-breadcrumb separator="/">
                  <el-breadcrumb-item :to="{ path: '/home' }"
                    >首页</el-breadcrumb-item
                  >
                  <el-breadcrumb-item>仓库管理</el-breadcrumb-item>
                </el-breadcrumb>
              </span>
            </div>
            <div class="top-bar-right">
              <span class="user-info">欢迎，{{ username }}</span>
            </div>
          </div>
          <!-- 仓库管理内容 -->
          <div class="content">
            <div class="page-title-bar">
              <h2 class="page-title">仓库列表</h2>
              <el-button type="primary" @click="goAddWarehouse" class="add-btn">
                <i class="el-icon-plus"></i> 新增仓库
              </el-button>
            </div>
            <div class="warehouse-list">
              <div class="card-list">
                <div
                  class="warehouse-card"
                  v-for="(item, index) in warehouseList"
                  :key="index"
                >
                  <div class="card-image">
                    <el-image
                      v-if="item.image"
                      :src="item.image"
                      fit="cover"
                      class="warehouse-img"
                    />
                    <div class="placeholder" v-else>
                      <el-icon>
                        <Picture />
                      </el-icon>
                      <span>暂无图片</span>
                    </div>
                  </div>
                  <div class="card-content">
                    <div class="card-header">
                      <h3 class="warehouse-name">{{ item.name }}</h3>
                      <span class="stock-tag">
                        <el-icon>
                          <Box />
                        </el-icon>
                        无人机数：{{ item.stock }}
                      </span>
                    </div>
                    <p class="location">位置：{{ item.location }}</p>
                    <p class="blurb" v-if="item.blurb">
                      简介：{{ item.blurb }}
                    </p>
                  </div>
                  <div class="card-actions">
                    <el-button
                      type="primary"
                      size="small"
                      @click="editWarehouse(item, index)"
                      >修改仓库</el-button
                    >
                  </div>
                </div>
                <div class="empty-state" v-if="warehouseList.length === 0">
                  <el-empty description="暂无仓库数据" />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="activeMenu === 'inbound'">
          <!-- 右侧内容区顶部栏 -->
          <div class="right-top-bar">
            <div class="top-bar-left">
              <span class="breadcrumb">
                <el-breadcrumb separator="/">
                  <el-breadcrumb-item :to="{ path: '/home' }"
                    >首页</el-breadcrumb-item
                  >
                  <el-breadcrumb-item>入库管理</el-breadcrumb-item>
                </el-breadcrumb>
              </span>
            </div>
            <div class="top-bar-right">
              <span class="user-info">欢迎，{{ username }}</span>
            </div>
          </div>
          <!-- 入库管理内容 -->
          <div class="content">
            <div class="page-title-bar">
              <h2 class="page-title">无人机仓库列表</h2>
            </div>
            <div class="card-list">
              <div
                class="warehouse-card"
                v-for="item in inboundList"
                :key="item.id"
              >
                <div class="card-image">
                  <el-image
                    v-if="item.uavPhoto"
                    :src="getUavImageUrl(item.uavPhoto)"
                    class="warehouse-img"
                  />
                  <div class="placeholder" v-else>
                    <el-icon>
                      <Picture />
                    </el-icon>
                    <span>暂无图片</span>
                  </div>
                </div>
                <div class="card-content">
                  <div class="card-header">
                    <h3 class="warehouse-name">{{ item.uavName }}</h3>
                    <span class="stock-tag">
                      <el-icon>
                        <Box />
                      </el-icon>
                      型号：{{ item.uavType }}
                    </span>
                  </div>
                  <p class="location">外观：{{ item.uavExterior }}</p>
                  <p class="location">
                    是否需要维护：{{ item.isMaintenance === "1" ? "是" : "否" }}
                  </p>
                  <p class="location">
                    无人机状态：{{ item.uavStatus === "1" ? "出库" : "未知" }}
                  </p>
                  <p class="location">
                    仓储位置：{{ item.warehouseName || "暂无" }}
                  </p>
                </div>
                <div class="card-actions">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleInbound(item)"
                    >入库</el-button
                  >
                </div>
              </div>
              <div class="empty-state" v-if="inboundList.length === 0">
                <el-empty description="暂无无人机数据" />
              </div>
            </div>
          </div>
        </div>
        <div v-if="activeMenu === 'drone-info'">
          <!-- 右侧内容区顶部栏 -->
          <div class="right-top-bar">
            <div class="top-bar-left">
              <span class="breadcrumb">
                <el-breadcrumb separator="/">
                  <el-breadcrumb-item :to="{ path: '/home' }"
                    >首页</el-breadcrumb-item
                  >
                  <el-breadcrumb-item>无人机信息管理</el-breadcrumb-item>
                </el-breadcrumb>
              </span>
            </div>
            <div class="top-bar-right">
              <span class="user-info">欢迎，{{ username }}</span>
            </div>
          </div>
          <!-- 无人机信息管理内容 -->
          <div class="content">
            <div class="page-title-bar">
              <h2 class="page-title">无人机列表</h2>
              <el-button
                type="primary"
                @click="goAddUav"
                class="add-btn"
                v-if="accountNumber == 'admin'"
              >
                <i class="el-icon-plus"></i> 新增无人机
              </el-button>
            </div>
            <div class="card-list">
              <div
                class="warehouse-card"
                v-for="item in uavList"
                :key="item.id"
                @click="showQrCode(item)"
              >
                <div class="card-image">
                  <el-image
                    v-if="item.image"
                    :src="item.image"
                    fit="cover"
                    class="warehouse-img"
                  />
                  <div class="placeholder" v-else>
                    <el-icon>
                      <Picture />
                    </el-icon>
                    <span>暂无图片</span>
                  </div>
                </div>
                <div class="card-content">
                  <div class="card-header">
                    <h3 class="warehouse-name">{{ item.uavName }}</h3>
                    <span class="stock-tag">
                      <el-icon>
                        <Box />
                      </el-icon>
                      型号：{{ item.uavType }}
                    </span>
                  </div>
                  <p class="location">
                    是否需要维护：{{ item.isMaintenance === "1" ? "是" : "否" }}
                  </p>
                  <p class="location">
                    无人机状态：{{ item.uavStatus === "0" ? "正常" : "维修" }}
                  </p>
                  <p class="location">
                    仓储位置：{{ item.warehouseName || "暂无" }}
                  </p>
                </div>
              </div>
              <div class="empty-state" v-if="uavList.length === 0">
                <el-empty description="暂无无人机数据" />
              </div>
            </div>
          </div>
        </div>
        <div v-if="activeMenu === 'outbound'">
          <!-- 右侧内容区顶部栏 -->
          <div class="right-top-bar">
            <div class="top-bar-left">
              <span class="breadcrumb">
                <el-breadcrumb separator="/">
                  <el-breadcrumb-item :to="{ path: '/home' }"
                    >首页</el-breadcrumb-item
                  >
                  <el-breadcrumb-item>出库管理</el-breadcrumb-item>
                </el-breadcrumb>
              </span>
            </div>
            <div class="top-bar-right">
              <span class="user-info">欢迎，{{ username }}</span>
            </div>
          </div>
          <!-- 出库管理内容 -->
          <div class="content">
            <div class="page-title-bar">
              <h2 class="page-title">待出库无人机列表</h2>
            </div>
            <div class="card-list">
              <div
                class="warehouse-card"
                v-for="item in outboundList"
                :key="item.id"
              >
                <div class="card-image">
                  <el-image
                    v-if="item.uavPhoto"
                    :src="getUavImageUrl(item.uavPhoto)"
                    class="warehouse-img"
                  />
                  <div class="placeholder" v-else>
                    <el-icon>
                      <Picture />
                    </el-icon>
                    <span>暂无图片</span>
                  </div>
                </div>
                <div class="card-content">
                  <div class="card-header">
                    <h3 class="warehouse-name">{{ item.uavName }}</h3>
                    <span class="stock-tag">
                      <el-icon>
                        <Box />
                      </el-icon>
                      型号：{{ item.uavType }}
                    </span>
                  </div>
                  <p class="location">外观：{{ item.uavExterior }}</p>
                  <p class="location">
                    是否需要维护：{{ item.isMaintenance === "1" ? "是" : "否" }}
                  </p>
                  <p class="location">
                    无人机状态：{{ item.uavStatus === "1" ? "出库" : "未知" }}
                  </p>
                  <p class="location">
                    仓储位置：{{ item.warehouseName || "暂无" }}
                  </p>
                </div>
                <div class="card-actions" style="justify-content: flex-start">
                  <el-button
                    type="primary"
                    size="small"
                    @click="goToOutboundDetail(item)"
                    >查看详情</el-button
                  >
                </div>
              </div>
              <div class="empty-state" v-if="outboundList.length === 0">
                <el-empty description="暂无出库无人机数据" />
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>

    <!-- 二维码弹窗 -->
    <el-dialog
      v-model="qrDialogVisible"
      title="无人机二维码"
      width="300px"
      :close-on-click-modal="false"
    >
      <div class="qr-container">
        <div v-if="currentQrCode" class="qr-code">
          <img :src="currentQrCode" alt="无人机二维码" class="qr-img" />
        </div>
        <div v-else class="qr-empty">
          <el-empty description="暂无二维码数据" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import {
  ElImage,
  ElEmpty,
  ElMessage,
  ElButton,
  ElDialog,
  ElBreadcrumb,
  ElBreadcrumbItem,
} from "element-plus";
import axios from "axios";
import { useRoute } from "vue-router";
import {
  OfficeBuilding,
  Upload,
  Suitcase,
  Download,
  Picture,
  Box,
} from "@element-plus/icons-vue";
const router = useRouter();
const route = useRoute();
const activeMenu = ref("warehouse");
const warehouseList = ref([]);
const uavList = ref([]);
const outboundList = ref([]);
const inboundList = ref([]);
const username = ref("");
const accountNumber = ref("");

// 二维码相关变量
const qrDialogVisible = ref(false);
const currentQrCode = ref("");

// 组件挂载时获取用户信息
onMounted(() => {
  const userInfoStr = localStorage.getItem("userInfo");
  if (userInfoStr) {
    const userInfo = JSON.parse(userInfoStr);
    username.value = userInfo.name;
    accountNumber.value = userInfo.accountNumber;
  }
});

function getImageUrl(base64) {
  if (!base64) return "";
  try {
    if (base64.startsWith("/9j/")) {
      return "data:image/jpeg;base64," + base64;
    }
    return base64;
  } catch {
    return "";
  }
}

async function fetchWarehouseList() {
  try {
    const res = await axios.get("/tielingpowergriduavservice/warehouse/list");
    if (res.data && res.data.code === 200) {
      warehouseList.value = (res.data.data || []).map((item) => ({
        name: item.warehouseName,
        location: item.warehouseAddress,
        image: getImageUrl(item.warehousePhoto),
        stock: item.courseCount || 0,
        blurb: item.warehouseBlurb || "",
        id: item.id,
      }));
    } else {
      warehouseList.value = [];
      ElMessage.error(res.data?.message || "获取仓库数据失败");
    }
  } catch (e) {
    warehouseList.value = [];
    ElMessage.error("请求仓库数据异常");
  }
}

function getUavImageUrl(base64) {
  if (!base64) return "";
  try {
    if (base64.startsWith("/9j/")) {
      return "data:image/jpeg;base64," + base64;
    }
    return base64;
  } catch {
    return "";
  }
}

async function fetchUavList() {
  try {
    const res = await axios.get("/tielingpowergriduavservice/uav/list");
    if (res.data && res.data.code === 200) {
      uavList.value = (res.data.data || []).map((item) => ({
        id: item.id,
        uavName: item.uavName,
        uavType: item.uavType,
        uavExterior: item.uavExterior,
        image: getUavImageUrl(item.uavPhoto),
        uavPhoto: item.uavPhoto,
        isMaintenance: item.isMaintenance,
        uavStatus: item.uavStatus,
        warehouseName: item.warehouseName || "暂无",
        qrCode: item.qrCode, // 存储二维码Base64数据
      }));
    } else {
      uavList.value = [];
      ElMessage.error(res.data?.message || "获取无人机数据失败");
    }
  } catch (e) {
    uavList.value = [];
    ElMessage.error("请求无人机数据异常");
  }
}

async function fetchOutboundList() {
  try {
    const res = await axios.get(
      "/tielingpowergriduavservice/task/listByStatus",
      {
        params: { status: "1" },
      }
    );
    if (res.data && res.data.code === 200) {
      outboundList.value = res.data.data || [];
    } else {
      outboundList.value = [];
      ElMessage.error(res.data?.message || "获取出库工单数据失败");
    }
  } catch (e) {
    outboundList.value = [];
    ElMessage.error("请求出库工单数据异常");
  }
}

async function fetchInboundList() {
  try {
    const res = await axios.get(
      "/tielingpowergriduavservice/uav/getUavByUavStatus",
      {
        params: { uavStatus: "1" },
      }
    );
    if (res.data && res.data.code === 200) {
      inboundList.value = res.data.data || [];
    } else {
      inboundList.value = [];
      ElMessage.error(res.data?.message || "获取无人机仓库列表失败");
    }
  } catch (e) {
    inboundList.value = [];
    ElMessage.error("请求无人机仓库列表异常");
  }
}

function handleInbound(item) {
  router.push({
    name: "UavInboundAdd",
    query: { uavId: item.id, uavName: item.uavName },
  });
}

function handleMenuSelect(key) {
  activeMenu.value = key;
  if (key === "warehouse") {
    fetchWarehouseList();
  } else if (key === "drone-info") {
    fetchUavList();
  } else if (key === "outbound") {
    fetchOutboundList();
  } else if (key === "inbound") {
    fetchInboundList();
  }
}

function goAddWarehouse() {
  router.push({ name: "WarehouseAdd" });
}

function goAddUav() {
  router.push({ name: "UavAdd" });
}

function editWarehouse(item) {
  router.push({
    name: "WarehouseEdit",
    query: { id: item.id },
  });
}

function goToOutboundDetail(item) {
  router.push({
    name: "UavOutboundDetail",
    query: { uavId: item.id, taskId: item.taskId },
  });
}

// 显示二维码弹窗
function showQrCode(item) {
  if (item.qrCode) {
    currentQrCode.value = item.qrCode; // 直接使用qrCode字段作为图片源
    qrDialogVisible.value = true;
  } else {
    ElMessage.warning("该无人机暂无二维码数据");
  }
}

onMounted(() => {
  const userInfoStr = localStorage.getItem("userInfo");
  if (userInfoStr) {
    const userInfo = JSON.parse(userInfoStr);
    username.value = userInfo.name;
  }

  if (route.query.tab === "drone-info") {
    activeMenu.value = "drone-info";
    fetchUavList();
  } else if (route.query.tab === "outbound") {
    activeMenu.value = "outbound";
    fetchOutboundList();
  } else if (route.query.tab === "inbound") {
    activeMenu.value = "inbound";
    fetchInboundList();
  } else {
    activeMenu.value = "warehouse";
    fetchWarehouseList();
  }
});

watch(
  () => route.query.tab,
  (newTab) => {
    if (newTab === "outbound") {
      activeMenu.value = "outbound";
      fetchOutboundList();
    } else if (newTab === "drone-info") {
      activeMenu.value = "drone-info";
      fetchUavList();
    } else if (newTab === "warehouse") {
      activeMenu.value = "warehouse";
      fetchWarehouseList();
    } else if (newTab === "inbound") {
      activeMenu.value = "inbound";
      fetchInboundList();
    }
  }
);
</script>

<style scoped>
.drone-warehouse-home {
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  display: flex;
  flex: 1;
}

.sidebar {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 30px;
  background-color: #2c3e50;
}

.sidebar-title {
  display: flex;
  align-items: center;
  margin-bottom: 40px;
  color: #fff;
  font-size: 18px;
  font-weight: 500;
}

.el-menu-vertical-demo {
  background: transparent;
  border-right: none;
  width: 100%;
}

.el-menu-item {
  color: #fff;
  font-size: 16px;
  height: 48px;
  line-height: 48px;
}

.el-menu-item.is-active {
  background: #199893 !important;
  color: #fff !important;
}

.main-content {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: #f8fafc;
  padding: 0;
}

.right-top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 0 20px;
  height: 50px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  z-index: 9;
}

.right-top-bar .top-bar-left {
  display: flex;
  align-items: center;
}

.right-top-bar .breadcrumb {
  font-size: 14px;
  color: #666;
}

.right-top-bar .top-bar-right {
  color: #333;
}

.right-top-bar .user-info {
  line-height: 50px;
}

.content {
  flex: 1;
  padding: 30px 50px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  overflow-x: hidden;
  max-height: calc(100vh - 100px);
}

.page-title-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e2e8f0;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
  display: flex;
  align-items: center;
}

.page-title::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 20px;
  background-color: #3498db;
  margin-right: 10px;
  border-radius: 2px;
}

.add-btn {
  background-color: #3498db;
  border-color: #3498db;
  transition: all 0.3s;
}

.add-btn:hover {
  background-color: #2980b9;
  border-color: #2980b9;
}

.card-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: flex-start;
}

.warehouse-card {
  width: calc((100% - 80px) / 5);
  min-width: 200px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  max-height: 400px;
  display: flex;
  flex-direction: column;
}

.warehouse-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.card-image {
  width: 100%;
  height: 160px;
  overflow: hidden;
  position: relative;
}

.warehouse-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  transition: transform 0.5s ease;
}

.warehouse-card:hover .warehouse-img {
  transform: scale(1.05);
}

.placeholder {
  width: 100%;
  height: 160px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f8fafc;
  color: #95a5a6;
  font-size: 14px;
}

.placeholder i {
  font-size: 24px;
  margin-bottom: 8px;
  color: #bdc3c7;
}

.card-content {
  padding: 20px;
}

.card-header {
  display: flex;
  flex-direction: column;
  margin-bottom: 12px;
}

.warehouse-name {
  font-size: 18px;
  font-weight: 500;
  color: #2c3e50;
  margin: 0 0 8px 0;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.stock-tag {
  display: inline-flex;
  align-items: center;
  padding: 3px 8px;
  font-size: 12px;
  color: #7f8c8d;
  background-color: #f1f5f9;
  border-radius: 4px;
  margin-bottom: 10px;
  width: fit-content;
}

.stock-tag i {
  margin-right: 5px;
  font-size: 12px;
}

.location {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0 0 15px 0;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 40px;
}

.blurb {
  font-size: 14px;
  color: #7f8c8d;
  margin-top: 10px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 36px;
}

.empty-state {
  width: 100%;
  padding: 60px 0;
  display: flex;
  justify-content: center;
}

.card-actions {
  position: absolute;
  right: 16px;
  bottom: 16px;
}

/* 二维码弹窗样式 */
.qr-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.qr-code {
  width: 200px;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.qr-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.qr-empty {
  width: 100%;
  padding: 40px 0;
  text-align: center;
}

/* 响应式优化 */
@media (max-width: 1400px) {
  .warehouse-card {
    width: calc((100% - 60px) / 4);
  }
}

@media (max-width: 1200px) {
  .warehouse-card {
    width: calc((100% - 40px) / 3);
  }
}

@media (max-width: 992px) {
  .warehouse-card {
    width: calc((100% - 20px) / 2);
  }
}

@media (max-width: 768px) {
  .warehouse-card {
    width: 100%;
  }
}
</style>
